<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>自定义HttpClient</title>
        <link rel='stylesheet prefetch' href='https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css'>
        <link rel="stylesheet" type="text/css" href="${ctx}/css/global.min.css"/>
        <link rel="stylesheet" type="text/css" href="${ctx}/css/indexCodeMirror.min.css"/>
        <link rel="stylesheet" type="text/css" href="${ctx}/css/swiper.min.css"/>
        <link rel="stylesheet" type="text/css" href="${ctx}/css/common.css"/>
        <link href="${ctx}/css/jquery-ui.css" rel="stylesheet">

        <script src="${ctx}/js/jquery.js"></script>
        <script src="${ctx}/js/jquery-ui.js"></script>

        <style>
            label.mt {
                /*margin: 10px;*/
                margin-top: 12px;
                /*margin-bottom: 20px;*/
            }

            div.mtb {
                margin-top: 10px;
                margin-bottom: 10px;
            }

            #dialog-link {
                padding: .4em 1em .4em 20px;
                text-decoration: none;
                position: relative;
            }

            #dialog-link span.ui-icon {
                margin: 0 5px 0 0;
                position: absolute;
                left: .2em;
                top: 50%;
                margin-top: -8px;
            }

            #dialog p {
                padding-left: 60px;
            }
        </style>
        <script>
            var my$ = $.noConflict();
        </script>
    </head>
    <body>
        <div class="container mtb" style="margin-left: 5%;">

            <div class="row mtb">
                <h3 class="page-header" style="margin: -10px 0 20px; width: 85%">接口测试工具</h3>
                <div class="container t-small-margin mtb">
                    <!--  <label class="mt">接口地址:</label>-->
                    <select id="type_select" class="selected form-select-button form-control"
                            style="display: inline-block;width: 7%">
                        <option value="GET">GET</option>
                        <option value="POST" selected>POST</option>
                    </select><input type="text" class="form-control" id="url_input"
                                    style="display: inline-block;width: 78%" value=""><br>
                    <label class="mt">消息头:</label>
                    <input type="text" class="form-control" id="header_input" title='{"A":"XX","B":"XX"}'
                           style="width: 85%">

                    <label class="mt">消息体:</label>
                    <div class="container t-small-margin" style="margin-top: -10px">
                        <!--  start 各个模块代码 -->
                        <form name="main" onsubmit="return false">
                            <div class="editor-box1">
                                <div class="float-left relative" style="width: 85%">
                                    <!-- json编辑器 -->
                                    <div id="editor" style="width: 100%">
                                        <textarea id="code" name="code"></textarea>
                                        <div id="resize">
                                            <i class="icon-bars"></i>
                                        </div>
                                    </div>
                                    <!-- 功能 -->
                                    <div class="t-huge-margin">
                                        <div class="btn-group">
                                            <button class="copy hide display-none"></button>
                                            <input type="submit" class="btn btn-primary" name="validate"
                                                   data-ga="validate"
                                                   id="validate" value="send">

                                            <button id="dialog-link" class="btn btn-primary" style="margin-left: 10px;">
                                                保存
                                            </button>
                                            <button type="reset" class="btn btn-primary" title="刷新页面"
                                                    onclick="location.reload()" style="margin-left: 10px;">刷新
                                            </button>

                                        </div>
                                        <div class="checkbox-primary">
                                            <input type="checkbox" id="loadChecked" checked="">
                                            <label for="loadChecked">记忆</label>
                                        </div>
                                        <button type="button" class="btn absolute "
                                                style="bottom: 0px;right: 5px;z-index: 9"
                                                id="clearContext" data-html="index">清空报文
                                        </button>
                                    </div>
                                </div>

                            </div>
                        </form>
                        <!-- 校验结果 -->
                        <div class="with-icon display-none" id="jsonlintBox">
                            <i class="icon-info-sign" id="jsonlintIcon"></i>
                            <pre class="content" id="jsonlintResult">请贴入要格式化的JSON代码</pre>
                        </div>
                    </div>
                </div>


                <div class="mtb" style="width: 85%">
                    <label class="mt">返回结果:</label>
                    <textarea class="well" id="showResult"
                              style="width: 100%; height: 200px;resize: none; margin-left: 10px" disabled>

                    </textarea>
                </div>
            </div>


            <!-- ui-dialog -->
            <div id="dialog" title="测试案例信息">
                <p>
                    <label>案例名称:</label> <input type="text" class="form-control" id="requestName"
                                                style="width: 50%; display: inline-block"><br>

                </p>
                <p>
                    <label>成功标志:</label>
                    <input type="text" class="form-control" id="successFlag"
                           style="width: 50%; display: inline-block"><br>
                </p>
                <p>
                    <label>是否公开:</label>
                    <select id="isPublic" class="selected form-select-button form-control"
                            style="display: inline-block; width: 25%">
                        <option value="1">公开</option>
                        <option value="0" selected>不公开</option>
                    </select>
                </p>
            </div>
        </div>
        <script src="${ctx}/js/global.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="${ctx}/js/lzma.js" type="text/javascript" charset="utf-8"></script>
        <script src="${ctx}/js/indexCodeMirror.min.js" type="text/javascript" charset="utf-8"></script>
        <script>
            //根据DOM元素的id构造出一个编辑器================================================================================================================================================================================================
            var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
                mode: 'application/json', //设置json模式
                lineNumbers: true, //是否显示左边换行术字
                lineWrapping: false, //是否折叠
                foldGutter: true,
                indentUnit: 4,
                gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
            });
        </script>
        <!--<script src="./static/bejson/js/jsonlint.js" type="text/javascript" charset="utf-8"></script>-->
        <script src="${ctx}/js/bejson_index20200722.min.js" type="text/javascript" charset="utf-8"></script>


        <script type="text/javascript">

            //声明一些用于保存测试成功案例信息的变量
            var url_Success;
            var type_Success;
            var headers_Success;
            var bodys_Success;

            //监听codemirror输入，买按一下键盘，存储一次编辑器内容
            document.onkeyup = function () {
                $.zui.store.set('lastJsonData', editor.getValue());
                $.zui.store.set('lastUrlDate', $("#url_input").val());
                $.zui.store.set('lastTypeDate', $("#type_select").val());
                $.zui.store.set('lastHeaderDate', $("#header_input").val());
            };


            //判断request中是否存在 RequestMessage,如果存在则直接返现,不从Local Storage中获取
            var lastChecked = $.zui.store.get('lastLoadChecked');
            <c:if test="${requestMessage!=null}">
            $.zui.store.set('lastJsonData', '${requestMessage.requestBody}');
            $.zui.store.set('lastUrlDate', '${requestMessage.url}');
            $.zui.store.set('lastTypeDate', '${requestMessage.requestMethod}');
            $.zui.store.set('lastHeaderDate', '${requestMessage.requestHeader}');
            lastChecked = "yes";
            </c:if>
            //初始化loadChecked
            if (lastChecked && lastChecked === 'no') {
                $('#loadChecked').attr('checked', false);
            } else {
                $('#loadChecked').attr('checked', 'checked');
            }

            //初始化上一次json数据
            var lastJson = $.zui.store.get('lastJsonData');
            if (lastJson && (!lastChecked || lastChecked === 'yes')) {
                if (typeof lastJson == 'object') {
                    editor.setValue(JSON.stringify(lastJson));
                } else {
                    editor.setValue(lastJson.toString());
                }
            }
            var lastUrl = $.zui.store.get('lastUrlDate');
            if (lastUrl && (!lastChecked || lastChecked === 'yes')) {
                if (typeof lastUrl == 'object') {
                    $("#url_input").val(JSON.stringify(lastUrl))
                } else {
                    $("#url_input").val(lastUrl.toString())
                }
            }
            var lastType = $.zui.store.get('lastTypeDate');
            if (lastType && (!lastChecked || lastChecked === 'yes')) {
                if (typeof lastType == 'object') {
                    $("#type_select").val(JSON.stringify(lastType))
                } else {
                    $("#type_select").val(lastType.toString())
                }
            }
            var lastHeader = $.zui.store.get('lastHeaderDate');
            if (lastHeader && (!lastChecked || lastChecked === 'yes')) {
                if (typeof lastHeader == 'object') {
                    $("#header_input").val(JSON.stringify(lastHeader))
                } else {
                    $("#header_input").val(lastHeader.toString())
                }
            }

            //清空编辑器的内容
            $("#clearContext").click(function () {
                editor.setValue("");
            });


            //发送请求
            $("#validate").click(function () {
                if ("send" != $(this).val()) {
                    alert("请求发送中,请勿点击");
                    return;
                }
                //获取必要参数
                var url = $("#url_input").val();
                var type = $("#type_select").val();
                var headers = $("#header_input").val();
                var bodys = editor.getValue();

                //校验url
                if (url == "") {
                    alert("请求地址不能为空");
                    doNotCheck();
                    return;
                }

                //如果是GET请求,并或者请求体为空时不做json格式校验
                if ("" == bodys || "GET" == type) {
                    doNotCheck();
                }

                //校验请求头格式
                try {
                    if ("" != headers) {
                        JSON.parse(headers);
                    }
                } catch (e) {
                    alert("请求头格式有误");
                    doNotCheck();
                    return
                }

                //校验报文格式
                try {
                    if ("POST" == type && "" != bodys) {
                        JSON.parse(bodys);
                    }
                } catch (e) {
                    alert("请求报文格式有误");
                    return
                }
                $(this).val("send...");


                //发请求获取响应

                my$.ajax({
                    url: '${ctx}/requestMessage/try.do',
                    type: 'POST',  // 默认为GET
                    data: {
                        requestHeader: headers,
                        requestMethod: type,
                        url: url,
                        requestBody: bodys
                    },
                    timeout: 5500, // 超时时间
                    /* beforeSend: function (xhr) {
                         console.log(xhr);
                         console.log('发送前')
                     },*/
                    success: function (result) {

                        if (result.success) {
                            url_Success = url;
                            type_Success = type;
                            headers_Success = headers;
                            bodys_Success = bodys;
                        }

                        try {
                            JSON.parse(result.message);
                            my$("#showResult").text(jsonFormat(result.message));
                        } catch (e) {
                            my$("#showResult").text(result.message);
                        }
                        my$("#validate").val("send");
                    },
                    error: function (xhr, textStatus) {
                        console.log('错误');
                        console.log(xhr);
                        if (textStatus=='timeout') {
                            my$("#showResult").text("请求超时了");
                        }
                        my$("#validate").val("send");
                    }
                })


            });


            function doNotCheck() {
                event.preventDefault();
                $("#validate").attr("disabled", false).val("send");
                $("#jsonlintBox").removeClass("alert-danger alert")
            }


            my$("#dialog").dialog({
                autoOpen: false,
                width: 400,
                buttons: [
                    {
                        text: "确认",
                        click: function () {
                            var that = my$(this);
                            var requestName = my$("#requestName").val();
                            var isPublic = my$("#isPublic").val();
                            var requestMethod = my$("#type_select").val();
                            var url = my$("#url_input").val();
                            var requestHeader = my$("#header_input").val();
                            var successFlag = my$("#successFlag").val();
                            var requestBody = editor.getValue();

                            //校验名称是否为空
                            if (requestName == "") {
                                alert("名称不能为空");
                                return
                            }

                            //校验该案例是否调试成功
                            if (url != url_Success || requestMethod != type_Success || requestHeader != headers_Success || requestBody != bodys_Success) {
                                alert("不能保存未调试成功的案例");
                                return
                            }

                            //校验成功标识是否为Json格式
                            try {
                                if ("" != successFlag) {
                                    JSON.parse(successFlag);
                                }
                            } catch (e) {
                                alert("成功标识必须是json格式");
                                return
                            }

                            //发ajax请求保存测试案例
                            my$.ajax({
                                url: '${ctx}/requestMessage/save.do',
                                type: 'POST',  // 默认为GET
                                data: {
                                    requestName: requestName,
                                    isPublic: isPublic,
                                    requestMethod: requestMethod,
                                    url: url,
                                    requestHeader: requestHeader,
                                    requestBody: requestBody,
                                    successFlag: successFlag
                                },
                                timeout: 5000, // 超时时间
                                success: function (result) {
                                    if (result.success) {
                                        alert("保存成功");
                                        that.dialog("close");
                                    } else {
                                        alert(result.message);
                                    }

                                },
                                error: function (xhr, textStatus) {
                                    alert("调用保存接口失败,请重试");
                                }
                            });

                        }
                    },
                    {
                        text: "取消",
                        click: function () {
                            my$(this).dialog("close");
                        }
                    }
                ]
            });
            my$("#dialog-link").click(function (event) {
                my$("#dialog").dialog("open");
                event.preventDefault();
            });
            my$("#dialog-link, #icons li").hover(
                function () {
                    my$(this).addClass("ui-state-hover");
                },
                function () {
                    my$(this).removeClass("ui-state-hover");
                }
            );


            function jsonFormat(text_value) {
                if (text_value == "") {
                    alert("不能为空");
                    return false;
                } else {
                    var res = "";
                    for (var i = 0, j = 0, k = 0, ii, ele; i < text_value.length; i++) {//k:缩进，j:""个数
                        ele = text_value.charAt(i);
                        if (j % 2 == 0 && ele == "}") {
                            k--;
                            for (ii = 0; ii < k; ii++) ele = "    " + ele;
                            ele = "\n" + ele;
                        } else if (j % 2 == 0 && ele == "{") {
                            ele += "\n";
                            k++;
                            debugger;
                            for (ii = 0; ii < k; ii++) ele += "    ";
                        } else if (j % 2 == 0 && ele == ",") {
                            ele += "\n";
                            for (ii = 0; ii < k; ii++) ele += "    ";
                        } else if (ele == "\"") j++;
                        res += ele;
                    }
                    return res;
                }
            }
        </script>

    </body>
</html>